package com.atguigu.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.SctpChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author: 叶子
 * @date: 2022/02/19 08:44
 **/
public class MyServer {
    public static void main(String[] args) {
//        创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//在bossGroup增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入一个netty提供的IdleStateHandler
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            /*
                             * 1.IdleStateHandler 是netty提供的处理空闲状态的处理器
                             * 2.long readerIdleTime 表示多长时间没有读，就会发送一个心跳检测包，检测是否处于连接状态
                             * 3.long writerIdleTime 表示多长时间没有写，就会发送一格心跳检测包，检测是否处于连接状态
                             * 4.long allIdleTime 表示多长时间没有读写，就会发送一格心跳检测包，检测是否处于连接状态
                             * 5.当IdleStateEvent触发后，就会传递给管道的下一个handler去处理，通过调用下一个handler的userEventTiggered
                             * 在该方法中去处理IdleStateEvent
                             */
                            //加入一个对空闲检测进一步处理的handler(自定义)
                            pipeline.addLast(new MyServerHandler());
                        }
                    });
//        启动服务器
            ChannelFuture channelFutrue = serverBootstrap.bind(7000).sync();
            channelFutrue.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}